package com.zzyl.service.impl;

import cn.hutool.core.bean.BeanUtil;
import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.date.LocalDateTimeUtil;
import cn.hutool.core.text.CharSequenceUtil;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.json.JSONUtil;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.zzyl.base.PageResponse;
import com.zzyl.constant.Constants;
import com.zzyl.dto.AlertRuleDto;
import com.zzyl.entity.AlertData;
import com.zzyl.entity.AlertRule;
import com.zzyl.mapper.AlertDataMapper;
import com.zzyl.mapper.AlertRuleMapper;
import com.zzyl.mapper.DeviceMapper;
import com.zzyl.mapper.UserRoleMapper;
import com.zzyl.service.AlertRuleService;
import com.zzyl.vo.AlertRuleVo;
import com.zzyl.vo.DeviceDataVo;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.data.redis.core.BoundHashOperations;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.format.DateTimeFormatter;
import java.time.temporal.ChronoUnit;
import java.util.ArrayList;
import java.util.List;
import java.util.concurrent.TimeUnit;
import java.util.stream.Collectors;


@Slf4j
@Service
public class AlertRuleServiceImpl implements AlertRuleService {

    @Autowired
    private AlertRuleMapper alertRuleMapper;
    @Autowired
    private StringRedisTemplate redisTemplate;

    /**
     * 新增报警规则
     * @param alertRuleDto 报警规则请求模型
     */
    @Override
    public void createRule(AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.insert(alertRule);
    }

    /**
     * 分页条件查询
     *
     * @param pageNum       页码
     * @param pageSize      页面大小
     * @param alertRuleName 报警规则名称
     * @param productKey    产品key
     * @param functionName  功能名称
     * @return 分页结果
     */
    @Override
    public PageResponse<AlertRuleVo> getAlertRulePage(Integer pageNum, Integer pageSize, String alertRuleName, String productKey, String functionName) {
        PageHelper.startPage(pageNum, pageSize);
        Page<AlertRuleVo> page = alertRuleMapper.page(alertRuleName, productKey, functionName);
        //添加提示
        page.getResult().forEach(alertRuleVo -> {
            String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRuleVo.getFunctionName(), alertRuleVo.getOperator(), alertRuleVo.getValue(), alertRuleVo.getDuration());
            alertRuleVo.setRules(alertReason);
        });

        return PageResponse.of(page, AlertRuleVo.class);
    }

    /**
     * 删除报警
     *
     * @param id 报警规则id
     */
    @Override
    public void deleteAlertRule(Long id) {
        alertRuleMapper.deleteByPrimaryKey(id);
    }

    /**
     * 修改报警
     *
     * @param id           报警规则id
     * @param alertRuleDto 报警规则更新请求模型
     */
    @Override
    public void updateAlertRule(Long id, AlertRuleDto alertRuleDto) {
        AlertRule alertRule = BeanUtil.toBean(alertRuleDto, AlertRule.class);
        alertRuleMapper.updateByPrimaryKeySelective(alertRule);
    }

    /**
     * 查询报警信息
     *
     * @param id 报警规则id
     * @return 报警信息
     */
    @Override
    public AlertRuleVo readAlertRule(Long id) {
        AlertRule alertRule = alertRuleMapper.selectByPrimaryKey(id);
        return BeanUtil.toBean(alertRule, AlertRuleVo.class);
    }

    /**
     * 启用或禁用
     *
     * @param id     报警id
     * @param status 报警规则状态
     */
    @Override
    public void enableOrDisable(Long id, Integer status) {
        alertRuleMapper.updateStatus(id, status);
    }

    @Override
    public void alarmAction() {
//        查询是否有规则
        int count = alertRuleMapper.selectCount();
        log.info("rule_count={}", count);
        if (count == 0) {
//            没有任何规则
            log.error("当前没有规则，报警过滤结束");
            return;
        }
//        查询所有设备上报的数据，查询Redis中设备上报的最后一条数据
        BoundHashOperations<String, String, String> boundHashOps = redisTemplate.boundHashOps(Constants.DEVICE_LASTDATA_CACHE_KEY);
        List<String> jsonList = boundHashOps.values();
        log.info("jsonList={}",jsonList);
        if (CollUtil.isEmpty(jsonList)){
//            设备没有上报数据
            log.error("当前没有设备上报数据，报警过滤结束");
            return;
        }
        List<DeviceDataVo> dataVoList = new ArrayList<>();
//        对上报数据进行格式化 List<jsonStr> List<DeviceDataVo>
        jsonList.forEach(jsonStr -> {
            dataVoList.addAll(JSONUtil.toList(jsonStr, DeviceDataVo.class));
        });
        if (CollUtil.isEmpty(dataVoList)){
//            设备没有上报数据
            log.error("当前没有设备上报数据，报警过滤结束");
            return;
        }
        log.info("dataVoList={}", dataVoList);
//        调用报警处理器
        this.alarmHandler(dataVoList);
    }

    /**
     * 报警处理器
     * @param dataVoList
     */
    private void alarmHandler(List<DeviceDataVo> dataVoList) {
//        遍历设备上报的数据
        for (DeviceDataVo vo : dataVoList) {
//            判断数据时间，找到1分钟内的数据
            long second = LocalDateTimeUtil.between(vo.getAlarmTime(), LocalDateTime.now(), ChronoUnit.SECONDS);
            if (second > 60){
                log.info("当前数据时间{}，超过1分钟，报警过滤结束",vo.getAlarmTime());
                continue;
            }
//        查询设备对应的产品和物模型的报警规则
            List<AlertRule> ruleList = alertRuleMapper.selectByCondition(vo.getProductKey(), vo.getFunctionId());
//        判断是否有规则
            if (CollUtil.isEmpty(ruleList)){
                log.error("当前产品{}和物模型{}没有报警规则，报警过滤结束",vo.getProductKey(),vo.getFunctionId());
                continue;
            }
//        如果有规则，遍历规则，去进行报警过滤
            for (AlertRule alertRule : ruleList) {
//            如果当前规则 是针对某一个设备的，需要判断数据是不是这个设备的数据
                if (!"-1".equals(alertRule.getIotId())){
                    if (!alertRule.getIotId().equals(vo.getIotId())){
                        continue;
                    }
                }
                log.info("当前报警规则={}",alertRule);
                log.info("当前上报数据={}",vo);
//            如果当前规则 是针对所有的设备，去过滤报警
                alertRuleFilterHander(alertRule,vo);
            }
        }
    }

    @Autowired
    private DeviceMapper deviceMapper;
    @Autowired
    private UserRoleMapper userRoleMapper;

    //设备维护人员的角色名称
    @Value("${zzyl.alert.deviceMaintainerRole}")
    private String deviceMaintainerRole;
    //超级管理员的角色名称
    @Value("${zzyl.alert.managerRole}")
    private String managerRole;

    private void alertRuleFilterHander(AlertRule alertRule, DeviceDataVo vo) {
//        判断生效时间
//        消息上报时间
        LocalTime alarmTime = vo.getAlarmTime().toLocalTime();
//        处理规则中的 生效时间，string -> time,time
        String period = alertRule.getAlertEffectivePeriod();
        String[] split = period.split("~");
        LocalTime begin = LocalTime.parse(split[0], DateTimeFormatter.ofPattern("HH:mm:ss"));
        LocalTime end = LocalTime.parse(split[1], DateTimeFormatter.ofPattern("HH:mm:ss"));
//        判断上报时间是否在 begin和end中
        if (alarmTime.isBefore(begin) || alarmTime.isAfter(end)){
            log.error("当前不在报警时间内");
            return;
        }
//        判断上报物模型数据阈值
        Float dataValue = Float.parseFloat(vo.getDataValue());
//        获取阈值数据
        Float value = alertRule.getValue();
        String operator = alertRule.getOperator();

        String trigger_key = Constants.ALERT_TRIGGER_COUNT_PREFIX + vo.getIotId() + ":" + vo.getFunctionId() + ":" + alertRule.getId();

        if ("<".equals(operator) && dataValue >= value ||
            ">=".equals(operator) && dataValue < value){
            log.error("data={}，value={}，数据正常不需要报警",dataValue,value);
//            删除redis的报警数
            redisTemplate.delete(trigger_key);
            return;
        }
//        沉默周期的key
        String silence_key = Constants.ALERT_SILENT_PREFIX + vo.getIotId() + ":" + vo.getFunctionId() + ":" + alertRule.getId();
//        判断沉默周期
        Boolean b = redisTemplate.hasKey(silence_key);
        if (b){
            log.info("还在沉默周期");
//           还在沉默周期内，不报警
            return;
        }
//        判断持续周期
        Integer duration = alertRule.getDuration();
//        到redis中获取 触发次数
        String count = redisTemplate.opsForValue().get(trigger_key);
        int triggerCount = count == null ? 0 : Integer.parseInt(count);
        if ((triggerCount+1) < duration){
//            触发次数小于持续周期，不报警
            log.info("触发次数小于持续周期，不报警");
            Long increment = redisTemplate.opsForValue().increment(trigger_key);
            log.info("当前的触发次数={}",increment);
            return;
        }
//        删除Redis的报警数
        redisTemplate.delete(trigger_key);
//        添加沉默周期
        redisTemplate.opsForValue().set(silence_key,"1",alertRule.getAlertSilentPeriod(), TimeUnit.MINUTES);

//        通过4层校验，当前的数据需要报警
        log.info("**************通过4层校验，准备报警");

        //获取消息的消费者
        List<Long> consumerIds = null;
        if (ObjectUtil.equals(0, alertRule.getAlertDataType())) {
            //如果是老人报警数据，需要通知绑定老人的护理员。根据iotId查询老人绑定的护理员
            if(vo.getLocationType() == 0){
                consumerIds = deviceMapper.selectNursingIdsByIotIdWithElder(vo.getIotId());
            }else if(vo.getLocationType() == 1 && vo.getPhysicalLocationType() == 2){
                consumerIds = deviceMapper.selectNursingIdsByIotIdWithBed(vo.getIotId());
            }
        } else {
            //如果是设备报警数据，需要通知设备维护人员。根据指定角色名称查询相关用户
            consumerIds = userRoleMapper.selectUserIdsByRoleName(deviceMaintainerRole);
        }
        //查询超级管理员，超级管理员无论什么消息都会接收
        List<Long> managerIds = userRoleMapper.selectUserIdsByRoleName(managerRole);
        List<Long> allConsumerIds = CollUtil.addAllIfNotContains(consumerIds, managerIds);
        allConsumerIds = CollUtil.distinct(allConsumerIds);

        //新增报警数据
        insertAlertData(vo, alertRule, allConsumerIds);
    }

    @Autowired
    private AlertDataMapper alertDataMapper;

    /**
     * 新增报警数据
     *
     * @param deviceDataVo 设备上报数据
     * @param alertRule    报警规则
     * @param consumerIds  消费者id列表
     * @return 报警数据
     */
    private void insertAlertData(DeviceDataVo deviceDataVo, AlertRule alertRule, List<Long> consumerIds) {
        String alertReason = CharSequenceUtil.format("{}{}{},持续{}个周期就报警", alertRule.getFunctionName(), alertRule.getOperator(), alertRule.getValue(), alertRule.getDuration());
        AlertData alertData = BeanUtil.toBean(deviceDataVo, AlertData.class);
        alertData.setAlertRuleId(alertRule.getId());
        alertData.setAlertReason(alertReason);
        alertData.setType(alertRule.getAlertDataType());
        alertData.setStatus(0);

        List<AlertData> list = consumerIds.stream().map(id -> {
            AlertData dbAlertData = BeanUtil.toBean(alertData, AlertData.class);
            dbAlertData.setUserId(id);
            return dbAlertData;
        }).collect(Collectors.toList());
        alertDataMapper.batchInsert(list);
    }
}
